<?php

namespace app\api\service;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;

class User
{
    /**
     * 保存用户数据
     * @param $data
     * @throws Exception
     */
    public static function saveUser($data): bool
    {
        $model=new \app\admin\model\User();
        $row=$model->where(['open_id'=>$data['open_id']])->find();
        $data['update_time']=time();
        if(!$row){//新增
            $data['create_time']=time();
            $id=$model->insertGetId($data);
            if(!$id){
                throw new Exception('操作失败，请重试');
            }
            return $id;
        }else{
            if($row['status']!=1){
                throw new Exception('用户被冻结');
            }
            $res=$model->where(['id'=>$row['id']])->save($data);
            if(!$res){
                throw new Exception('操作失败，请重试');
            }
            return $row['id'];
        }
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public static function saveUserById($data, $uid){
        $model=new \app\admin\model\User();
        $row=$model->find($uid);
        if(!$row){
            throw new Exception('用户不存在');
        }
        $res=$row->save($data);
        if(!$res){
            throw new Exception('保存失败');
        }
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public static function getUser($uid){
        $model=new \app\admin\model\User();
        $row=$model->field('id,nick_name,avatar_url,phone,status')->where(['id'=>$uid])->find();
        if(!$row){
            throw new Exception('用户不存在');
        }
        if($row['status']!=1){
            throw new Exception('用户被冻结');
        }
        return $row->toArray();
    }
}